<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->
    <div class="tree-panel">
      <div class="head-container">
        <el-input
          v-model="projectName"
          placeholder="请输入培训项目"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
          @keyup.enter.native="filterTree"
        />
      </div>
      <el-tree
        ref="tree"
        :data="projectOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <el-col :span="20" style="padding: 20px">
      <!-- 搜索区域 -->
      <el-form
        :model="queryParams"
        inline
        size="small"
        v-show="showSearch"
        label-width="80px"
      >
        <el-form-item label="证书名称">
          <el-input
            v-model="queryParams.certificateTemplateName"
            placeholder="请输入证书名称关键词"
            clearable
            @keyup.enter.native="handleQuery"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryParams.createTimeRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            style="width: 260px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- 按钮组 -->
        <el-col :span="24">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 0;
            "
          >
            <!-- 左侧按钮 -->
            <div style="display: flex; gap: 10px">
              <el-button type="primary" plain @click="handleExport"
                >导出</el-button
              >
              <el-button
                type="primary"
                plain
                @click="openCertificateDialog(false)"
                >新增/编辑证书模板1</el-button
              >
              <el-button
                type="primary"
                plain
                @click="openCertificateTemplateEditor"
                >新增/编辑证书模板2</el-button
              >
              <el-button type="primary" plain @click="handleViewTemplate"
                >查看证书模板</el-button
              >
              <el-button type="primary" plain @click="handleDeleteTemplate"
                >删除证书模板</el-button
              >
              <el-button type="primary" plain @click="handleRemark"
                >备注</el-button
              >
            </div>

            <!-- 右侧按钮 -->
            <div style="display: flex; gap: 10px">
              <column-config-dialog-vue
                :showSearch.sync="showSearch"
                :columns="tableColumns"
                @queryTable="getList"
              ></column-config-dialog-vue>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="certificateTemplateList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column
          label="证书名称"
          align="center"
          prop="certificateTemplateName"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateTemplateName')
              .visible
          "
        />
        <el-table-column
          label="培训项目"
          align="center"
          prop="trainingProjectName"
          v-if="
            tableColumns.find((col) => col.prop === 'trainingProjectName')
              .visible
          "
        />
        <el-table-column
          label="创建人"
          align="center"
          prop="createdBy"
          v-if="tableColumns.find((col) => col.prop === 'createdBy').visible"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createdTime"
          v-if="tableColumns.find((col) => col.prop === 'createdTime').visible"
        >
          <template slot-scope="scope">
            {{ scope.row.createdTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          v-if="tableColumns.find((col) => col.prop === 'remark').visible"
        />
        <el-table-column
          label="操作"
          width="280px"
          align="center"
          class-name="small-padding fixed-width"
          v-if="tableColumns.find((col) => col.prop === 'operation').visible"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEditTemplateById(scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="text" @click="handleCopy(scope.row)"
              >复制</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleViewCertificate(scope.row)"
              >查看证书</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleRemarkRow(scope.row)"
              >备注</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDeleteTemplate(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改题组管理对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="800px"
        custom-class="dialog-custom"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- 第一行：题组名称 和 题组题型 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="题组名称" prop="groupName">
                <el-input
                  v-model="form.groupName"
                  placeholder="请输入题组名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题组题型" prop="groupType">
                <el-select
                  v-model="form.groupType"
                  placeholder="请选择题组题型"
                >
                  <el-option
                    v-for="dict in dict.type.question_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：项目类别 -->
          <el-form-item label="项目类别" prop="trainingProjectId">
            <el-cascader
              v-model="form.trainingProjectId"
              :options="projectOptions"
              :props="{
                checkStrictly: true,
                emitPath: false, //只传入子节点的id
                value: 'id',
                label: 'label',
                children: 'children',
              }"
              placeholder="请选择项目类别"
              clearable
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-dialog>

      <!-- 备注 -->
      <RemarkDialogVue
        :visible.sync="remarkDialogVisible"
        :record-id="currentRecordId"
        :remark-history="remarkList"
        :remark-type="'8'"
      />
      <!-- 新增/编辑证书模板1 -->
      <CertificateTemplateDialog
        ref="certificateDialog"
        :visible.sync="certificateDialogVisible"
        @success="handleCertificateSuccess"
        v-show="certificateStep === 1"
      />
      <!-- 新增/编辑证书模板2 -->
      <certificate-template-editor
        ref="certificateTemplateEditor"
        :visible.sync="certificateTemplateEditorVisible"
        :template-data="certificateTemplateData"
        @success="handleCertificateEditSuccess"
        @prev-step="handlePrevStep"
        v-show="certificateStep === 2"
      />
      <!-- 查看证书模板 -->
      <view-certificate-template-dialog
        ref="viewCertificateTemplateDialog"
        :template-data="viewCertificateTemplateData"
        :visible.sync="viewCertificateTemplateDialogVisible"
        @edit-template="handleEditTemplate"
        v-show="certificateStep === 3"
      />
    </el-col>
  </div>
</template>

<script>
import {
  listCertificateTemplate,
  getCertificateTemplate,
  delCertificateTemplate,
  addCertificateTemplate,
  updateCertificateTemplate,
  addCertificateTemplateInfo,
  getCertificateTemplateInfo,
  editCertificateTemplate,
  copyCertificateTemplate,
} from "@/api/certificate/certificateTemplate";
import { listRemarksByParams } from "@/api/training/remarks";
import { projectTreeSelect } from "@/api/training/projects";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 备注
import RemarkDialogVue from "../../../components/Certificate/template/RemarkDialog.vue";
// 新增/编辑证书模板1
import CertificateTemplateDialog from "../../../components/Certificate/template/CertificateTemplateDialog.vue";
//新增/编辑证书模板2
import CertificateTemplateEditor from "../../../components/Certificate/template/CertificateTemplateEditor.vue";
// 查看证书模板
import ViewCertificateTemplateDialog from "../../../components/Certificate/template/ViewCertificateTemplateDialog.vue";
export default {
  name: "CertificateTemplate",
  dicts: ["question_type", "relate_status"],
  components: {
    ColumnConfigDialogVue,
    RemarkDialogVue,
    CertificateTemplateDialog,
    CertificateTemplateEditor,
    ViewCertificateTemplateDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书模板表格数据
      certificateTemplateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        certificateTemplateName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [
          { required: true, message: "题组名称不能为空", trigger: "blur" },
        ],
        groupType: [
          { required: true, message: "题组题型不能为空", trigger: "change" },
        ],
        trainingProjectId: [
          { required: true, message: "项目类别不能为空", trigger: "change" },
        ],
      },
      //新增数据定义
      //树形结构数据
      // 所有部门树选项
      projectName: "",
      projectOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 缓存字典数据
      dictCache: {
        question_type: {},
        relate_status: {},
      },
      // 列显隐
      tableColumns: [
        { prop: "certificateTemplateName", label: "证书名称", visible: true },
        { prop: "trainingProjectName", label: "培训项目", visible: true },
        { prop: "createdBy", label: "创建人", visible: true },
        { prop: "createdTime", label: "创建时间", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      //备注
      remarkDialogVisible: false,
      currentRecordId: "",
      remarkList: [], // 存储备注历史
      //新增/编辑证书模板1
      certificateDialogVisible: false,
      //新增/编辑证书模板2
      certificateTemplateEditorVisible: false,
      // 证书模板步骤控制
      certificateStep: 1, // 1: CertificateTemplateDialog, 2: CertificateTemplateEditor
      certificateTemplateData: null, // 存储模板中的数据
      // 查看证书模板
      viewCertificateTemplateDialogVisible: false,
      viewCertificateTemplateData: null,
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
  },
  filters: {
    formatDate(value) {
      if (value) {
        return moment(value).format("YYYY-MM-DD HH:mm:ss");
      }
      return "";
    },
  },
  methods: {
    async loadDicts() {
      this.dictCache.question_type = this.dict.label.question_type;
      this.dictCache.relate_status = this.dict.label.relate_status;
    },
    /** 管理列表 */
    getList() {
      this.loading = true;
      listCertificateTemplate(this.queryParams).then((response) => {
        this.certificateTemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        certificateTemplateId: null,
        ceritificateTemplateName: null,
        trainingProjectId: null,
        trainingProjectName: null,
        backgroundUrl: null,
        description: null,
        delFlag: null,
        createdBy: null,
        updatedBy: null,
        createdTime: null,
        updatedTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.createTimeRange) {
        this.queryParams.createStartTime = this.queryParams.createTimeRange[0];
        this.queryParams.createEndTime = this.queryParams.createTimeRange[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        trainingProjectName: null,
        projectId: this.queryParams.projectId, // 保留项目ID，因为它是通过树节点选择的
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.certificateTemplateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加证书模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const certificateTemplateId = row.certificateTemplateId || this.ids;
      getCertificateTemplate(certificateTemplateId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改证书模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.certificateTemplateId != null) {
            updateCertificateTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificateTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const certificateTemplateIds = row.certificateTemplateId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除证书模板编号为"' + certificateTemplateIds + '"的数据项？'
        )
        .then(function () {
          return delCertificateTemplate(certificateTemplateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 删除证书模板
    handleDeleteTemplate(row) {
      const certificateTemplateIds = row.certificateTemplateId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除证书模板编号为"' + certificateTemplateIds + '"的数据项？'
        )
        .then(function () {
          return delCertificateTemplate(certificateTemplateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/certificateTemplate/export",
        {
          ...this.queryParams,
        },
        `certificateTemplate_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //树形结构
    filterTree() {
      this.$refs.tree.filter(this.projectName);
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.trainingProjectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    flattenTree(tree) {
      let result = [];
      tree.forEach((node) => {
        result.push({ id: node.id, label: node.label });
        if (node.children && node.children.length > 0) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    // 切换搜索显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 刷新表格数据
    refreshTable() {
      this.getList();
    },
    // 切换排序列显示
    toggleSort() {
      // 根据实际需求实现排序列的显示/隐藏逻辑
      this.$message.info("排序列功能待实现");
    },

    //证书

    // 备注
    handleRemark() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行备注");
        return;
      }

      const row = this.certificateTemplateList.find(
        (item) => item.certificateTemplateId === this.ids[0]
      );
      if (!row) return;

      this.currentRecordId = row.certificateTemplateId;

      var params = { foreignId: row.certificateTemplateId, remarkType: "8" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },

    //新增/编辑证书模板1
    // 打开证书模板弹窗
    openCertificateDialog(isEdit = false) {
      this.certificateStep = 1;
      this.certificateDialogVisible = true;
    },
    // 显式传递数据到编辑器组件
    passDataToEditor() {
      if (
        this.certificateTemplateData &&
        this.$refs.certificateTemplateEditor
      ) {
        this.$refs.certificateTemplateEditor.setTemplateData(
          this.certificateTemplateData
        );
      }
    },
    handleCertificateSuccess(templateData) {
      this.certificateTemplateData = templateData;

      console.log("传递的数据:", templateData);

      // 关闭第一个对话框，打开第二个
      this.certificateDialogVisible = false;
      this.certificateStep = 2;
      this.$nextTick(() => {
        this.certificateTemplateEditorVisible = true;
        this.passDataToEditor();
      });
    },
    //新增/编辑证书模板2
    openCertificateTemplateEditor() {
      this.certificateTemplateEditorVisible = true;
    },
    // handleCertificateEditSuccess(editedTemplateData) {
    //   // 合并完整的模板数据
    //   const finalData = {
    //     ...this.certificateTemplateData,
    //     ...editedTemplateData,
    //   };

    //   console.log("完整证书模板数据:", finalData);

    //   // 获取所有选中的字段（包括证书字段和自定义字段）
    //   const allSelectedFields = [
    //     ...(finalData.fields?.requiredFields || []),
    //     ...(finalData.fields?.customFields?.map((f) => f.value) || []),
    //   ];

    //   const selectedTemplate = this.certificateTemplateList.find(
    //     (item) => item.certificateTemplateId === this.ids[0]
    //   );

    //   const params = {
    //     certificateTemplateId: selectedTemplate.certificateTemplateId || null,
    //     certificateTemplateName: finalData.basicInfo.name,
    //     trainingProjectId: finalData.basicInfo.trainingProjectId,
    //     paperType: finalData.basicInfo.paperType,
    //     paperSize: finalData.basicInfo.paperSize,
    //     backgroundUrl: finalData.basicInfo.backgroundImage,
    //     certificateFieldList: allSelectedFields.map((fieldName) => {
    //       // 查找字段的格式设置
    //       const fieldFormat = finalData.fieldFormats?.[fieldName] || {};

    //       // 查找字段的标签
    //       const fieldLabel =
    //         finalData.fields?.optionalFields?.find((f) => f.value === fieldName)
    //           ?.label || fieldName;

    //       return {
    //         fieldKey: fieldName,
    //         fieldLabel: fieldLabel,
    //         fontFamily: fieldFormat.fontFamily || "SimHei",
    //         fontSize: fieldFormat.fontSize
    //           ? parseInt(fieldFormat.fontSize)
    //           : 18,
    //         fontColor: fieldFormat.color || "#000000",
    //         fontWeight: fieldFormat.bold ? "bold" : "normal",
    //         italic: fieldFormat.italic || false,
    //         underline: fieldFormat.underline || false,
    //         textAlign: fieldFormat.alignment || "center",
    //         lineHeight: fieldFormat.lineHeight
    //           ? parseFloat(fieldFormat.lineHeight)
    //           : 1.2,
    //         letterSpacing: fieldFormat.letterSpacing
    //           ? parseFloat(fieldFormat.letterSpacing)
    //           : 0,
    //       };
    //     }),
    //   };
    //   console.log("提交参数:", params);

    //   if (params.certificateTemplateId) {
    //     // 修改
    //     editCertificateTemplate(params).then((res) => {
    //       console.log("更新成功:", res);
    //       // 刷新列表数据
    //       this.getList();
    //     });
    //   } else {
    //     // 新增
    //     addCertificateTemplateInfo(params).then((res) => {
    //       console.log("添加成功:", res);
    //       // 关闭对话框并重置状态
    //       this.certificateTemplateEditorVisible = false;
    //       this.certificateStep = 1;
    //       this.certificateTemplateData = {};
    //       // 刷新列表数据
    //       this.getList();
    //     });
    //   }
    // },
    // 处理上一步

    handleCertificateEditSuccess(editedTemplateData) {
      // 合并完整的模板数据
      const finalData = {
        ...this.certificateTemplateData,
        ...editedTemplateData,
      };

      console.log("完整证书模板数据:", finalData);

      // 获取所有选中的字段（包括证书字段和自定义字段）
      const allSelectedFields = [
        ...(finalData.fields?.requiredFields || []),
        ...(finalData.fields?.customFields?.map((f) => f.value) || []),
      ];

      // 修复：添加对 ids 数组的检查，确保有选中的记录
      let selectedTemplate = null;
      if (this.ids && this.ids.length > 0) {
        selectedTemplate = this.certificateTemplateList.find(
          (item) => item.certificateTemplateId === this.ids[0]
        );
      }

      const params = {
        // 修复：只有当 selectedTemplate 存在时才使用其 ID，否则设为 null
        certificateTemplateId: selectedTemplate
          ? selectedTemplate.certificateTemplateId
          : null,
        certificateTemplateName: finalData.basicInfo.name,
        trainingProjectId: finalData.basicInfo.trainingProjectId,
        paperType: finalData.basicInfo.paperType,
        paperSize: finalData.basicInfo.paperSize,
        backgroundUrl: finalData.basicInfo.backgroundImage,
        certificateFieldList: allSelectedFields.map((fieldName) => {
          // 查找字段的格式设置
          const fieldFormat = finalData.fieldFormats?.[fieldName] || {};

          // 查找字段的标签
          const fieldLabel =
            finalData.fields?.optionalFields?.find((f) => f.value === fieldName)
              ?.label || fieldName;

          return {
            fieldKey: fieldName,
            fieldLabel: fieldLabel,
            fontFamily: fieldFormat.fontFamily || "SimHei",
            fontSize: fieldFormat.fontSize
              ? parseInt(fieldFormat.fontSize)
              : 18,
            fontColor: fieldFormat.color || "#000000",
            fontWeight: fieldFormat.bold ? "bold" : "normal",
            italic: fieldFormat.italic || false,
            underline: fieldFormat.underline || false,
            textAlign: fieldFormat.alignment || "center",
            lineHeight: fieldFormat.lineHeight
              ? parseFloat(fieldFormat.lineHeight)
              : 1.2,
            letterSpacing: fieldFormat.letterSpacing
              ? parseFloat(fieldFormat.letterSpacing)
              : 0,
          };
        }),
      };
      console.log("提交参数:", params);

      // 更安全的检查方式：检查 certificateTemplateId 是否存在且不为 null
      if (params.certificateTemplateId) {
        // 修改
        editCertificateTemplate(params).then((res) => {
          console.log("更新成功:", res);
          // 刷新列表数据
          this.getList();
        });
      } else {
        // 新增
        addCertificateTemplateInfo(params).then((res) => {
          console.log("添加成功:", res);
          // 关闭对话框并重置状态
          this.certificateTemplateEditorVisible = false;
          this.certificateStep = 1;
          this.certificateTemplateData = {};
          // 刷新列表数据
          this.getList();
        });
      }
    },
    handlePrevStep() {
      this.certificateTemplateEditorVisible = false;
      this.certificateStep = 1;
      this.certificateDialogVisible = true;
    },
    // 查看证书模板
    handleViewTemplate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行查看");
        return;
      }

      const selectedTemplate = this.certificateTemplateList.find(
        (item) => item.certificateTemplateId === this.ids[0]
      );
      if (!selectedTemplate) {
        this.$message.warning("未找到选中的模板");
        return;
      }

      getCertificateTemplateInfo(selectedTemplate.certificateTemplateId).then(
        (res) => {
          const templateData = res.data;
          // 设置当前模板数据并显示对话框
          this.viewCertificateTemplateData = templateData;

          console.log("查看模板数据:", templateData);

          this.viewCertificateTemplateDialogVisible = true;
        }
      );
    },

    // 处理编辑事件
    handleEditTemplate(templateData) {
      // 先关闭查看对话框
      this.viewCertificateTemplateDialogVisible = false;

      // 设置编辑数据
      this.certificateTemplateData = templateData;

      // 打开编辑器对话框
      this.$nextTick(() => {
        this.certificateStep = 2;
        this.certificateTemplateEditorVisible = true;

        // 确保DOM更新后再调用子组件方法
        this.$nextTick(() => {
          if (this.$refs.certificateTemplateEditor) {
            this.$refs.certificateTemplateEditor.setTemplateData(templateData);
          }
        });
      });
    },

    //操作栏部分
    //编辑
    handleEditTemplateById(row) {
      getCertificateTemplateInfo(row.certificateTemplateId).then((res) => {
        const templateData = res.data;

        // 构造符合 CertificateTemplateEditor 组件要求的数据结构
        const editorData = {
          basicInfo: {
            name: templateData.certificateTemplateName,
            trainingProjectId: templateData.trainingProjectId,
            paperType: templateData.paperType,
            paperSize: templateData.paperSize,
            backgroundImage: templateData.backgroundUrl,
          },
          fields: {
            optionalFields: [
              {
                label: "姓名",
                value: "name",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "name"
                ),
              },
              {
                label: "证件编号",
                value: "idNumber",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "idNumber"
                ),
              },
              {
                label: "培训项目",
                value: "trainingProject",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "trainingProject"
                ),
              },
              {
                label: "有效年限",
                value: "validYears",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "validYears"
                ),
              },
              {
                label: "发证日期",
                value: "issueDate",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "issueDate"
                ),
              },
              {
                label: "起始有效期",
                value: "startDate",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "startDate"
                ),
              },
              {
                label: "截止有效期",
                value: "endDate",
                selected: templateData.certificateFieldList?.some(
                  (f) => f.fieldKey === "endDate"
                ),
              },
            ],
            customFields:
              templateData.certificateFieldList
                ?.filter(
                  (f) =>
                    ![
                      "name",
                      "idNumber",
                      "trainingProject",
                      "validYears",
                      "issueDate",
                      "startDate",
                      "endDate",
                    ].includes(f.fieldKey)
                )
                .map((f) => ({ value: f.fieldKey })) || [],
          },
          fieldFormats: {},
        };

        // 设置字段格式
        if (templateData.certificateFieldList) {
          templateData.certificateFieldList.forEach((field) => {
            editorData.fieldFormats[field.fieldKey] = {
              fontFamily: field.fontFamily || "SimHei",
              fontSize: field.fontSize?.toString() || "18",
              color: field.fontColor || "#000000",
              alignment: field.textAlign || "center",
              letterSpacing: field.letterSpacing || 0,
              lineHeight: field.lineHeight || 1.2,
              backgroundColor: "#007aff",
              borderColor: "#dcdfe6",
              italic: field.italic || false,
              underline: field.underline || false,
              superscript: false,
              subscript: false,
              bold: field.fontWeight === "bold",
            };
          });
        }

        // 设置模板数据并打开编辑器
        this.certificateTemplateData = editorData;
        this.certificateStep = 2;
        this.$nextTick(() => {
          this.certificateTemplateEditorVisible = true;

          // 确保 DOM 更新后再调用子组件方法
          this.$nextTick(() => {
            if (this.$refs.certificateTemplateEditor) {
              this.$refs.certificateTemplateEditor.setTemplateData(editorData);
            }
          });
        });
      });
    },
    // 查看证书
    handleViewCertificate(row) {
      getCertificateTemplateInfo(row.certificateTemplateId).then((res) => {
        const templateData = res.data;

        this.viewCertificateTemplateData = templateData;
        this.certificateStep = 3; // 设置为查看组件
        this.$nextTick(() => {
          this.viewCertificateTemplateDialogVisible = true;
        });
      });
    },
    // 备注行
    handleRemarkRow(row) {
      var params = { foreignId: row.certificateTemplateId, remarkType: "8" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },

    // 复制
    handleCopy(row) {
      copyCertificateTemplate(row.certificateTemplateId).then((res) => {
        this.$message.success("复制成功");
        this.getList();
      });
    },
  },
  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 100%;
}

.tree-panel {
  width: 360px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}

.el-form {
  margin-top: 20px;
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}
.dialog-custom {
  min-height: 500px !important;
  max-height: 600px !important;
  overflow-y: auto;
}
</style>
